import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'

export default class extends React.PureComponent {
  
  static propTypes = {
    date: PropTypes.number
  }
  
  static defaultProps = {
    date: Date.now()
  }
  
  state = {
    // 设置初始的时间
    time: 0,
  }

  componentDidMount() {
    // 每秒都更新一下时间
    this.interval = setInterval(() => {
      this.setState(state => ({ ...state, time: Date.now() }))
    }, 1000)
  }

  componentWillUnmount() {
    // 当不再渲染，停止计时器
    clearInterval(this.interval)
  }

  formatTime = () => {
    return moment().format('LLLLs')
  }

  render() {
    const { time } = this.state
    const formatTime = this.formatTime(time)
    return (
      <React.Fragment>
        {`${formatTime}秒`}
      </React.Fragment>
    )
  }
}